package com.wxapp.common.util.enums;

import com.wxapp.common.base.util.bean.SpringUtils;
import com.wxapp.common.constant.base.IBaseEnum;
import com.wxapp.common.constant.pojo.vm.PEnumVm;
import com.wxapp.common.constant.properties.CatchCommonProperties;
import com.wxapp.common.util.reflect.ReflectUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EnumUtil {
    private final static String packageFrist = "com.wxapp.";
    private final static String packageSplit = ".";
    private final static String packageCenter = "api.enums.";
    private EnumUtil() {
    }

    /**
     * 通过枚举值获取枚举
     */
    public static <T extends IBaseEnum<String>> T getEnumByValue(String value, Class<T> tClass) {
        T[] objects = tClass.getEnumConstants();
        var first = Arrays.stream(objects).filter(s -> s.getValue() != null && String.valueOf(s.getValue()).equalsIgnoreCase(value)).findFirst();
        return first.orElse(null);
    }

    /**
     * 通过名称获取枚举值
     */
    public static <T extends IBaseEnum<String>> T getEnumByName(String name, Class<T> tClass) {
        T[] objects = tClass.getEnumConstants();
        var getNameMethod = ReflectUtil.getMethod("name", tClass);
        var first = Arrays.stream(objects).filter(s -> {
            var data = ReflectUtil.invokeMethod(getNameMethod, s);
            return data != null && String.valueOf(data).equalsIgnoreCase(name);
        }).findFirst();
        return first.orElse(null);
    }

    /**
     * 通过名称获取枚举值
     */
    public static  List<PEnumVm> getEnumByClass(String className) {
        try {
            var name = CatchCommonProperties.name.toLowerCase();
            Class<?> tClass = Class.forName(packageFrist + name +packageSplit+ packageCenter + className);
            if (!Enum.class.getName().equals(tClass.getSuperclass().getCanonicalName())) {
                throw new RuntimeException("不是枚举类");
            }
            List<PEnumVm> result = new ArrayList<>();
            var getNameMethod = ReflectUtil.getMethod("name", tClass);
            var getValueMethod = ReflectUtil.getMethod("getValue", tClass);
            var getDescMethod = ReflectUtil.getMethod("getDesc", tClass);
            Arrays.stream(tClass.getEnumConstants()).forEach(s -> result.add(new PEnumVm(String.valueOf(ReflectUtil.invokeMethod(getNameMethod, s)),
                    String.valueOf(ReflectUtil.invokeMethod(getValueMethod, s)),
                    String.valueOf(ReflectUtil.invokeMethod(getDescMethod, s)))));
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
